package com.chzc.server;

import com.chzc.entity.DevilMessage;
import com.chzc.initializer.DevilProducerInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;


/**
 * 消息发送者
 */
public class DevilProducer {

    /**
     * broker地址
     */
    private final String host;

    /**
     * broker端口号
     */
    private final int port;

    private Bootstrap bootstrap;

    public DevilProducer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private ChannelFuture channelFuture;

    private EventLoopGroup group;

    /**
     * 消息发送者建立连接
     */
    public void start() {
        group = new NioEventLoopGroup();

        bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.group(group);
        //自定义一个初始化类
        bootstrap.handler(new DevilProducerInitializer());
        try {
            this.channelFuture = bootstrap.connect(this.host, this.port).sync();
            channelFuture.channel();

//            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            group.shutdownGracefully();
        }
    }

    /**
     * 释放/关闭连接
     */
    public void release() {
        this.group.shutdownGracefully();
    }

    /**
     * 发送消息
     *
     * @param queueName
     * @param message
     */
    public void sendMag(String queueName, String message) {
        // 消息内容
        byte[] content = message.getBytes(StandardCharsets.UTF_8);
        // 消息长度
        int contentLen = message.getBytes(StandardCharsets.UTF_8).length;
        // 队列名称
        byte[] queue = queueName.getBytes(StandardCharsets.UTF_8);
        // 队列名称长度
        int queueLen = queueName.getBytes(StandardCharsets.UTF_8).length;

        DevilMessage devilMessage = new DevilMessage();
        devilMessage.setLen(contentLen);
        devilMessage.setContent(content);
        devilMessage.setMessageId("omq".getBytes(StandardCharsets.UTF_8));
        devilMessage.setMessageIdLen("omq".getBytes(StandardCharsets.UTF_8).length);
        devilMessage.setQueueName(queue);
        devilMessage.setQueueLen(queueLen);
        devilMessage.setStatus(1);
        devilMessage.setPingType(false);

        this.channelFuture.channel().writeAndFlush(devilMessage);
    }

    public static void main(String[] args) throws Exception {
//        new DevilClien("127.0.0.1", 7000).start();
    }
}
